package basework

import (
	"bytes"
	"encoding/binary"
	"lnzw/engine/log"
	nw "lnzw/engine/net/work"
	"lnzw/server/logic/codemapping"

	"go.uber.org/zap"
	"google.golang.org/protobuf/proto"
)

type NetWork[Req proto.Message, Res proto.Message] struct {
	nw.IProtoOther[Req, Res] `work:"run"`
}

func (w *NetWork[Req, Res]) Run() {
	defer func() {
		if err := recover(); err != nil {
			log.Logger.Error("work run failed", zap.Any("err", err))
		}
	}()
	w.Handle(w.GetConn(), w.GetRequest(), w.GetReply())
	_, mapping := codemapping.GetMapping(w.GetCode())
	if mapping.Res != nil {
		var buf bytes.Buffer
		bs := make([]byte, 4)
		binary.BigEndian.PutUint32(bs, uint32(w.GetCode()))
		buf.Write(bs)
		pbBs, err := proto.Marshal(w.GetReply())
		if err != nil {
			log.Logger.Error("proto marshal error", zap.Any("err", err))
			return
		}
		buf.Write(pbBs)
		w.GetConn().SendMsg(buf.Bytes())
	}
}
